<template>
  <div class="practiceContend">
    <div class="container">
      <section class="chooseCarType">
        <div class="topTitleTab">
          <span>当前位置：首页 > {{ subText }} > 模拟考试</span>
        </div>
      </section>
      <section class="practiceBox">
        <div class="practice_left">
          <div class="practice_left_top">
            <div class="left_top-left">
              <div class="left-top">
                <span class="tips">第01考台</span>
                <span class="title">理论考试</span>
              </div>
              <div class="left-bot">
                <span class="title">考生信息</span>
                <div class="studentCon">
                  <div class="s-top">
                    <div class="imgBox">
                      <img src="~/assets/images/peopleMr.png" alt="" />
                    </div>
                    <span class="subtext">{{ subText }}</span>
                  </div>
                  <div class="s-bot">
                    <span class="tips">考生姓名：学员</span>
                    <span class="tips">考试题数：{{ questionNum }}</span>
                    <span class="tips">考试时间：{{ time }}</span>
                    <span class="tips"
                      >满分{{ totalScore }}分，{{ passScore }}分合格</span
                    >
                  </div>
                </div>
              </div>
            </div>
            <div class="left_top-right">
              <span class="title">考试题目</span>
              <div class="question">
                <div class="question_title">
                  <span class="slotIndex"
                    >{{ currentIndex }}/{{ serialList.length }}</span
                  >
                  <span class="question_title">{{
                    currentQuestion.content
                  }}</span>
                </div>
                <div class="options">
                  <div
                    :class="[
                      optionItem.rightNor ? ' rightNor' : '',
                      optionItem.right ? ' right' : '',
                      optionItem.error ? ' error' : '',
                      'optionItem curp',
                    ]"
                    v-for="(optionItem, i) in currentQuestion.option"
                    :key="i"
                    @click="chooseOptions(currentQuestion, i, optionItem.value)"
                  >
                    <span class="curp">{{ optionItem.title }}</span>
                  </div>
                  <span
                    class="dxbtn"
                    v-if="currentQuestion.type == 2"
                    @click="setUserAnswer()"
                    >确定</span
                  >
                </div>
              </div>
            </div>
          </div>
          <div class="practice_left_bot">
            <div class="left">
              <div class="left-top">
                <span class="title">剩余时间</span>
                <span class="addColor">
                  <van-count-down
                    :time="time * 60 * 1000"
                    @finish="finish"
                    @change="onChange"
                  >
                    <template v-slot="timeData">
                      <span class="item">{{ timeData.hours }}</span
                      >: <span class="item">{{ timeData.minutes }}</span
                      >:
                      <span class="item">{{ timeData.seconds }}</span>
                    </template>
                  </van-count-down>
                </span>
              </div>
              <div class="left-top ml">
                <span class="title">提示信息</span>
                <!-- <span class="tips">判断题，请判断对错</span> -->
                <span class="tips" v-if="currentQuestion.type == 0"
                  >判断题，请选择对错</span
                >
                <span class="tips" v-if="currentQuestion.type == 1"
                  >单选题，请选择的正确答案</span
                >
                <span class="tips" v-if="currentQuestion.type == 2"
                  >多选题，请选择至少两个答案</span
                >
              </div>
            </div>
            <div class="btns">
              <span class="btn colorback" @click="backQuestion">上一题</span>
              <span class="btn colorback" @click="nextQuestion">下一题</span>
              <span class="btn submitBtnColor" @click="submitQuestions"
                >交卷</span
              >
            </div>
          </div>
        </div>
        <div class="practice_right">
          <!-- 题序 -->
          <section class="preface" v-if="questionList.length > 0">
            <div
              :class="[
                item.index == currentIndex
                  ? 'prefaceItem curp active'
                  : 'prefaceItem curp',
                item.right ? 'right' : '',
                item.error ? ' error' : '',
              ]"
              v-for="(item, i) in questionList"
              @click="choosequestion(item)"
            >
              <span>{{ item.index }}</span>
            </div>
          </section>
        </div>
      </section>
      <section class="imgInfo">
        <span class="title">图片信息</span>
        <div class="infoBox">
          <el-image
            v-if="
              currentQuestion.head_type == 'image' &&
              currentQuestion.head_img != ''
            "
            style="width: 100%; height: 100%"
            :src="currentQuestion.head_img"
            fit="contain"
            :preview-src-list="[currentQuestion.head_img]"
          >
          </el-image>
          <VueVideo
            :aspectRatio="'320:166'"
            :loop="true"
            :autoplay="true"
            :controls="false"
            :VideoSrc="currentQuestion.head_img"
            v-if="
              currentQuestion.head_type == 'video' &&
              currentQuestion.head_img != ''
            "
          ></VueVideo>
        </div>
      </section>
    </div>
  </div>
</template>
<script>
import VueVideo from "@/components/VueVideo.vue";
import { questionSerial, question, questionExamquestion } from "~/api/question";
export default {
  components: { VueVideo },
  data() {
    return {
      options: [
        { name: "A、违章行为" },
        { name: "B、违章行为" },
        { name: "C、违章行为" },
        { name: "D、违章行为" },
      ],
      flag: true,
      showserial: false,
      currentIndex: 1,
      userAnswer: null,
      optionsdx: [], //多选数组
      rightNum: 0, //答对
      errorNum: 0, //答对
      rate: 0, //正确率
      minutes: 45,
      seconds: 0,
      score: 0,
      errScore: 0,
      timeData: {
        hours: 0,
        minutes: 0,
        seconds: 0,
      },
    };
  },

  async asyncData({ app, query, params }) {
    let { sub, type, category, categorysub, group } = query;
    if(type){
      type = decodeURIComponent(type);
    }
  

    let axioxsParams = { course: sub, group: group, category: category };
    let axioxsParamsQ = {
      course: sub,
      group: group,
      category: category,
      question: 1,
    };
    let data = await questionExamquestion(axioxsParams);
    let dataQ = await questionExamquestion(axioxsParamsQ);
    let questionList = [],
      serialList = [];

    serialList = dataQ;
    questionList = dataQ;
    serialList.forEach((p, i) => {
      p.index = i + 1;
    });
    let confirmButtonText =
      "按交管部门通知，" +
      data.course +
      "考试系统全面更新。模拟考试考试下不能修改答案，每做一题，系统自动计算错误题数，及格标准为" +
      data.passScore +
      "分。";
    console.log(data);

    return {
      subText: data.category,
      sub: sub,
      group: group,
      type: type,
      category: category,
      serialList: serialList.length > 0 ? serialList : [],
      questionList: questionList,
      currentQuestion: serialList.length > 0 ? serialList[0] : {},
      questionNum: data.totalQuestion,
      confirmButtonText: confirmButtonText,
      categorysub: categorysub,
      config: data,
      totalScore: data.totalScore,
      passScore: data.passScore,
      time: data.time,
    };
  },
  watch:{
    errScore(val){
      if(val>(this.totalScore-this.passScore)){
        this.$confirm("考试确认窗口", {
        title: "您已经答错规定题数，不及格",
        confirmButtonText: "确认交卷",
        cancelButtonText: "继续答题",
        message: h("div", null, newDatas),
        showClose: false,
      })
        .then(() => {
          that.sendquery();
        })
        .catch(() => {});
      }
    }
  },
  methods: {  
    onChange(e) {
      this.timeData = e;
    },
    finish() {
      this.$alert("错题过多，已经不及格，", "考试确认窗口", {
        confirmButtonText: "确定",
        callback: () => {
          this.sendquery();
        },
      });
    },
    //请求题
    async getquestionList(arr) {
      var that = this;
      let acserialList = arr;
      if (!this.flag) {
        return;
      }
      this.flag = false;
      let questionList = await question({
        id: acserialList,
        course: this.sub,
        category: this.category,
        group: this.group,
      });
      this.flag = true;
      questionList.forEach((p) => {
        that.serialList.forEach((s) => {
          if (p.id == s.id && !s.content) s = Object.assign(s, p);
        });
      });
    },
    //答题
    chooseOptions(val, i, userAnswer) {
      var that = this;
      if (val.userAnswer) {
        return;
      }
      let currentQuestion = JSON.parse(JSON.stringify(val));
      if (currentQuestion.type == 0 || currentQuestion.type == 1) {
        //判断 、单选
        currentQuestion.userAnswer = userAnswer;
        if (userAnswer == currentQuestion.answer) {
          // 回答正确
          that.rightNum += 1;
          
          currentQuestion.option[i].right = true;
         that.score +=  currentQuestion.score;
          that.serialList.forEach((s) => {
            if (s.id == currentQuestion.id) s.right = true;
          });
        } else {
          // 回答错误
          that.errorNum += 1;
          currentQuestion.option[i].error = true;
          that.errScore +=  currentQuestion.score;
          that.serialList.forEach((s) => {
            if (s.id == currentQuestion.id) s.error = true;
          });
        }
        that.currentQuestion = currentQuestion;
        that.serialList.forEach((p) => {
          if (p.id == currentQuestion.id) p = Object.assign(p, currentQuestion);
        });
        setTimeout(function () {
          that.nextQuestion();
        }, 300);
      } else if (currentQuestion.type == 2) {
        //多选
        let userAnswer = [];
        currentQuestion.option[i].right = currentQuestion.option[i].right
          ? !currentQuestion.option[i].right
          : true;
        currentQuestion.option.forEach((p) => {
          if (p.right) userAnswer.push(p.value);
        });
        this.userAnswer = userAnswer;
        that.currentQuestion = currentQuestion;
      }
    },
    //多选确定
    setUserAnswer() {
      let that = this;
      let currentQuestion = JSON.parse(JSON.stringify(that.currentQuestion));
      currentQuestion.userAnswer = that.userAnswer.join(",");
      if (currentQuestion.userAnswer == currentQuestion.answer) {
        that.rightNum += 1;
         that.score +=  currentQuestion.score;
        that.serialList.forEach((s) => {
          if (s.id == currentQuestion.id) s.right = true;
        });
      } else {
        that.errorNum += 1;
         that.errScore +=  currentQuestion.score;
        that.serialList.forEach((s) => {
          if (s.id == currentQuestion.id) s.error = true;
        });
        that.serialList.forEach((p) => {
          if (p.id == currentQuestion.id) p = Object.assign(p, currentQuestion);
        });
      }
      setTimeout(function () {
        that.nextQuestion();
      }, 300);
    },
    //选择题序
    choosequestion(item) {
      if (!item.content) {
        let acserialList = [];
        let question = this.serialList.slice(
          item.index - 10,
          item.index - 1 + 10
        );
        question.forEach((p) => {
          acserialList.push(p.id);
        });
        this.getquestionList(acserialList).then(() => {
          this.currentQuestion = this.serialList[item.index - 1];
          this.currentIndex = item.index;
        });
      } else {
        // if(!this.serialList[this.index + 4].content)
        this.currentQuestion = this.serialList[item.index - 1];
        this.currentIndex = item.index;
      }
    },
    // 上一题
    backQuestion() {
      if (this.currentIndex == 1) {
        alert("已经是第一题了");
        return;
      }
      if (
        this.serialList[this.currentIndex - 5] &&
        !this.serialList[this.currentIndex - 5].content
      ) {
        let acserialList = [];
        let question = this.serialList.slice(
          this.currentIndex - 25,
          this.currentIndex - 1
        );
        question.forEach((p) => {
          acserialList.push(p.id);
        });

        this.getquestionList(acserialList);
      }
      this.currentIndex -= 1;
      this.currentQuestion = this.serialList[this.currentIndex - 1];
    },
    // 下一题
    nextQuestion() {
      if (this.currentIndex == this.serialList.length) {
        alert("已经是最后一题了");
        return;
      }
      if (
        this.serialList[this.currentIndex + 5] &&
        !this.serialList[this.currentIndex + 5].content
      ) {
        let acserialList = [];
        let question = this.serialList.slice(
          this.currentIndex + 5,
          this.currentIndex + 25
        );
        question.forEach((p) => {
          acserialList.push(p.id);
        });

        this.getquestionList(acserialList);
      }
      this.currentIndex += 1;
      this.currentQuestion = this.serialList[this.currentIndex - 1];
    },
    //倒计时
    add() {
      var _this = this;
      var time = window.setInterval(function () {
        if (_this.seconds === 0 && _this.minutes !== 0) {
          _this.seconds = 59;
          _this.minutes -= 1;
        } else if (_this.minutes === 0 && _this.seconds === 0) {
          _this.seconds = 0;
          window.clearInterval(time);
        } else {
          _this.seconds -= 1;
        }
      }, 1000);
    },
    num: function (n) {
      return n < 10 ? "0" + n : "" + n;
    },
    submitQuestions() {
      let confirmText = [
        "1、点击【确认交卷】，将提交考试成绩，结束考试。",
        "2、点击【继续答题】，将继续答题,倒计时结束无法继续答题。",
      ];
      const newDatas = [];
      const h = this.$createElement;
      for (const i in confirmText) {
        newDatas.push(h("p", null, confirmText[i]));
      }
      this.$confirm("考试确认窗口", {
        title: "考试确认窗口",
        confirmButtonText: "确认交卷",
        cancelButtonText: "继续答题",
        message: h("div", null, newDatas),
        showClose: false,
      })
        .then(() => {
          this.sendquery();
        })
        .catch(() => {});
    },
    sendquery() {
      let sub = this.sub;
      let category = this.category;
      let group = this.group;
      let sectionTotal = this.rightNum + this.errorNum;
      let questionNum = this.questionNum;
      let allTime = this.time * 60;

      let timeData = this.timeData;
      let Time =timeData.hours * 60 * 60 + timeData.minutes * 60 + timeData.seconds;
      let useTime = allTime - Time;
      let useminutes = parseInt(useTime / 60);
      let useseconds = useTime - useminutes * 60;

      let score = this.score;
      console.log(score)
      this.$router.push({
        name: "examination-practice-practiceDetails-id",
        query: {
          sub: sub,
          category: category,
          group: group,
          score: score,
          useminutes: useminutes,
          useseconds: useseconds,
          sectionTotal: sectionTotal,
          errorNum: this.errorNum,
          rightNum: this.rightNum,
          questionNum: questionNum,
        },
      });
    },
  },
  mounted() {
    //  this.add()
    this.$alert(this.confirmButtonText, {
      confirmButtonText: "确定",
      showClose: false,
      callback: (action) => {
        this.add();
      },
    });
  },
};
</script>

<style scoped lang='scss'>
@import "~/assets/css/practice.scss";
::v-deep {
  .el-checkbox__label {
    font-size: 16px;
  }
}
.vjs-custom-skin > .video-js .vjs-big-play-button {
  display: none !important;
}
</style>